#include <Mesh_IO/Mesh_IO.h>
#include <tool/libcell_tools_algorithm.h>
#include <Algorithm/points_cloud_algorithm.h>

#include <tool/libcell_tools_kd_node.h>
#include<Mesh/libcell_iterator.h>
#include "Arcroll.h"

#define quote lib_cell_quote

void my_test()
{
    Mesh mesh;
    Mesh_init(&mesh);
    _ReadPly_(&mesh,"184205.ply");
    //mesh_adjust_mesh_to_unit_hexahedron(&mesh);
 
    printf("num v:%d\n",mesh.num_v(&mesh));

    double *box=mesh_compute_bounding_box(&mesh);
    double temps[3]={box[3]-box[0],box[4]-box[1],box[5]-box[2]};

    for(int i=0;i<2;i++)
    {
        for(int j=0;j<2;j++)
        {
            if(temps[j]<temps[j+1])
            {
                double temp=temps[j];
                temps[j]=temps[j+1];
                temps[j+1]=temp;
            }
        } 
    }


    printf("%lf %lf %lf\n",temps[0],temps[1],temps[2]);
    //double * box=mesh_compute_bounding_box_from_node();

    Node* clus=get_cluster_pionts_from_mesh1(&mesh, 0.03* temps[1]);
    for(Node* nit=clus;nit!=NULL;nit=(Node*)(nit->Next))
    {
        Int_RB_Tree* tree=(Int_RB_Tree*)(nit->value);
        
        printf("%d\n",tree->size); 

    }

    Viewer_World_Manager vwm;
    viewer_world_manager_init(&vwm);
    Viewer_World *vw=vwm.create_world(&vwm,NULL);

    add_default_somethings(vw);

    Node* n= vw->create_something(vw,"Points");
    auto vs=(Viewer_Something*)(n->value);
    auto vp=(Viewer_Points*)(vs->evolution);

    Int_RB_Tree* tree=(Int_RB_Tree*)(clus->value);
    vp->Data_rows=tree->size;
    vp->Data=(float*)malloc(sizeof(float)*3*vp->Data_rows);
    int i=0;
    for(auto it=tree->begin(tree);it.it!=NULL;it++)
    {
        template_v* v=(template_v*)(it.second);
        vp->Data[i*3+0]=v->point[0];vp->Data[i*3+1]=v->point[1];
        vp->Data[i*3+2]=v->point[2];

        i++;
    }
    vp->set_color(vp,1,0,0,1);

    free_node(n);
 
    Viewer_Opengl_Interpreter voi;

    viewer_opengl_interpreter_initn(&voi,&vwm);
    voi.interpreter(&voi);


    viewer_opengl_interpreter_free(&voi);
    viewer_world_manager_free(&vwm);   

    free_node(clus);
    Mesh_free(&mesh);
}

#undef quote

int main()
{

    my_test();

    // Mesh mesh;
    // Mesh_init(&mesh);

    // _ReadPly_(&mesh,"184205.ply");


    // Mesh_free(&mesh);
    printf("end\n");

    return 0;
}

